//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package ciicos.views.service.impl;

import ciicos.base.ActionResult;
import ciicos.base.model.filter.RuleInfo;
import ciicos.base.vo.ListVO;
import ciicos.model.visiual.superQuery.ConditionJsonModel;
import ciicos.model.visiual.superQuery.SuperQueryConditionModel;
import ciicos.model.visiual.superQuery.SuperQueryJsonModel;
import ciicos.permission.controller.OrganizeController;
import ciicos.permission.model.authorize.AuthorizeConditionModel;
import ciicos.permission.model.organize.OrganizeDepartSelectorListVO;
import ciicos.permission.service.AuthorizeService;
import ciicos.permission.util.GenUtil;
import ciicos.util.GeneraterSwapUtil;
import ciicos.util.JsonUtil;
import ciicos.util.ServletUtil;
import ciicos.util.StringUtil;
import ciicos.util.UserProvider;
import ciicos.util.context.SpringContext;
import ciicos.views.entity.ViewsHmiEntity;
import ciicos.views.mapper.ViewsHmiMapper;
import ciicos.views.model.viewshmi.OrganizeAndViewsVO;
import ciicos.views.model.viewshmi.ViewsHmiForm;
import ciicos.views.model.viewshmi.ViewsHmiPagination;
import ciicos.views.service.ViewsHmiService;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ViewsHmiServiceImpl extends ServiceImpl<ViewsHmiMapper, ViewsHmiEntity> implements ViewsHmiService {
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private AuthorizeService authorizeService;

    public List<ViewsHmiEntity> getList(ViewsHmiPagination viewsHmiPagination) {
        return this.getTypeList(viewsHmiPagination, viewsHmiPagination.getDataType());
    }

    public List<ViewsHmiEntity> getTypeList(ViewsHmiPagination viewsHmiPagination, String dataType) {
        String userId = this.userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList();
        int total = 0;
        int viewsHmiNum = 0;
        QueryWrapper<ViewsHmiEntity> viewsHmiQueryWrapper = new QueryWrapper();
        List<String> allSuperIDlist = new ArrayList();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(viewsHmiPagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = (SuperQueryJsonModel)JsonUtil.getJsonToBean(viewsHmiPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);

            for(ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null && Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                    conditionjson.setFieldValue("[]");
                }

                conditionjson.setTableName(tableName);
            }

            List<String> allSuperList = new ArrayList();
            List<List<String>> intersectionSuperList = new ArrayList();
            int viewsHmiNum1 = 0;
            QueryWrapper<ViewsHmiEntity> viewsHmiSuperWrapper = new QueryWrapper();
            viewsHmiNum1 = this.generaterSwapUtil.getCondition(new SuperQueryConditionModel(viewsHmiSuperWrapper, superQueryList, matchLogic, "views_hmi"), new ViewsHmiEntity(), viewsHmiNum1);
            if (viewsHmiNum1 > 0) {
                List<String> viewsHmiList = (List)this.list(viewsHmiSuperWrapper).stream().map(ViewsHmiEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(viewsHmiList);
                intersectionSuperList.add(viewsHmiList);
            }

            superOp = matchLogic;
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = this.generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }

        boolean pcPermission = true;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("ciicos-origin").equals("pc");
        if (isPc && pcPermission && !this.userProvider.get().getIsAdministrator()) {
            Object viewsHmiObj = this.authorizeService.getCondition(new AuthorizeConditionModel(viewsHmiQueryWrapper, viewsHmiPagination.getMenuId(), "views_hmi"));
            if (ObjectUtil.isEmpty(viewsHmiObj)) {
                return new ArrayList();
            }

            viewsHmiQueryWrapper = (QueryWrapper)viewsHmiObj;
            if (viewsHmiQueryWrapper.getExpression().getNormal().size() > 0) {
                ++viewsHmiNum;
            }
        }

        if (!isPc && appPermission && !this.userProvider.get().getIsAdministrator()) {
            Object viewsHmiObj = this.authorizeService.getCondition(new AuthorizeConditionModel(viewsHmiQueryWrapper, viewsHmiPagination.getMenuId(), "views_hmi"));
            if (ObjectUtil.isEmpty(viewsHmiObj)) {
                return new ArrayList();
            }

            viewsHmiQueryWrapper = (QueryWrapper)viewsHmiObj;
            if (viewsHmiQueryWrapper.getExpression().getNormal().size() > 0) {
                ++viewsHmiNum;
            }
        }

        if (isPc) {
            if (ObjectUtil.isNotEmpty(viewsHmiPagination.getName())) {
                ++viewsHmiNum;
                viewsHmiQueryWrapper.lambda().like(ViewsHmiEntity::getName, viewsHmiPagination.getName());
            }

            if (ObjectUtil.isNotEmpty(viewsHmiPagination.getOrganizeid())) {
                ++viewsHmiNum;
                viewsHmiQueryWrapper.lambda().like(ViewsHmiEntity::getOrganizeid, viewsHmiPagination.getOrganizeid());
            }
        }

        List<String> intersection = this.generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }

            viewsHmiQueryWrapper.lambda().in(ViewsHmiEntity::getId, intersection);
        }

        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            viewsHmiQueryWrapper.lambda().and(t->t.in(ViewsHmiEntity::getId, finalAllSuperIDlist));
        }

        if (StringUtil.isEmpty(viewsHmiPagination.getSidx())) {
            viewsHmiQueryWrapper.lambda().orderByDesc(ViewsHmiEntity::getName);
        } else {
            try {
                String sidx = viewsHmiPagination.getSidx();
                ViewsHmiEntity viewsHmiEntity = new ViewsHmiEntity();
                Field declaredField = viewsHmiEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = ((TableField)declaredField.getAnnotation(TableField.class)).value();
                viewsHmiQueryWrapper = "asc".equals(viewsHmiPagination.getSort().toLowerCase()) ? (QueryWrapper)viewsHmiQueryWrapper.orderByAsc(value) : (QueryWrapper)viewsHmiQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        viewsHmiQueryWrapper.lambda().select(ViewsHmiEntity.class, (field) -> !field.getProperty().equals("items") && !field.getProperty().equals("svgcontent"));
        if (!"0".equals(dataType)) {
            return this.list(viewsHmiQueryWrapper);
        } else if ((total <= 0 || AllIdList.size() <= 0) && total != 0) {
            List<ViewsHmiEntity> list = new ArrayList();
            return viewsHmiPagination.setData(list, (long)list.size());
        } else {
            Page<ViewsHmiEntity> page = new Page(viewsHmiPagination.getCurrentPage(), viewsHmiPagination.getPageSize());
            IPage<ViewsHmiEntity> userIPage = this.page(page, viewsHmiQueryWrapper);
            return viewsHmiPagination.setData(userIPage.getRecords(), userIPage.getTotal());
        }
    }

    public QueryWrapper wrapperHandle(QueryWrapper<?> wrapper, String id, Class<?> aClass, String type, String tableName) {
        try {
            wrapper.apply(" 1=1 ", new Object[0]);

            for(RuleInfo info : this.generaterSwapUtil.getFilterCondition(id)) {
                String field = info.getField();
                if ((!"main".equals(type) || !field.contains("-")) && (!"main".equals(type) || !field.contains("_jnpf_")) && (!"sub".equals(type) || field.contains("-")) && (!"sub-jnpf".equals(type) || field.contains("_jnpf_"))) {
                    String fieldName = field;
                    String table = "";
                    if (field.contains("-")) {
                        fieldName = field.split("-")[1];
                    }

                    if (field.contains("_jnpf_")) {
                        fieldName = field.split("_jnpf_")[1];
                        table = field.split("_jnpf_")[0];
                        table = table.replace("jnpf_", "");
                    }

                    if (!"sub-jnpf".equals(type) || tableName.equals(table)) {
                        Field declaredField = aClass.getDeclaredField(fieldName);
                        declaredField.setAccessible(true);
                        String fieldDb = ((TableField)declaredField.getAnnotation(TableField.class)).value();
                        GenUtil genUtil = (GenUtil)JsonUtil.getJsonToBean(info, GenUtil.class);
                        genUtil.solveValue(wrapper, fieldDb);
                    }
                }
            }

            return wrapper;
        } catch (Exception var15) {
            return wrapper;
        }
    }

    public ViewsHmiEntity getInfo(String id) {
        QueryWrapper<ViewsHmiEntity> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(ViewsHmiEntity::getId, id);
        return (ViewsHmiEntity)this.getOne(queryWrapper);
    }

    public void create(ViewsHmiEntity entity) {
        this.save(entity);
    }

    public boolean update(String id, ViewsHmiEntity entity) {
        return this.updateById(entity);
    }

    public void delete(ViewsHmiEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }

    }

    public String checkForm(ViewsHmiForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }

        return countRecover;
    }

    public List<OrganizeDepartSelectorListVO> getDepartment() {
        ActionResult<ListVO<OrganizeDepartSelectorListVO>> listDepartment = SpringContext.getBean(OrganizeController.class).getListDepartment("0");
        return ((ListVO)listDepartment.getData()).getList();
    }

    public List<OrganizeAndViewsVO> getListByDepartment(String id) {
        QueryWrapper<ViewsHmiEntity> qw = new QueryWrapper();
        LambdaQueryWrapper<ViewsHmiEntity> vs = qw.lambda().eq(ViewsHmiEntity::getOrganizeid, id).eq(ViewsHmiEntity::getEnabledmark, "1");
        List<ViewsHmiEntity> list = this.list(vs);
        List<OrganizeAndViewsVO> viewsVOList = new ArrayList();

        for(ViewsHmiEntity viewsHmiEntity : list) {
            OrganizeAndViewsVO o = new OrganizeAndViewsVO();
            o.setFullName(viewsHmiEntity.getName());
            o.setChildren(new ArrayList());
            o.setHasChildren(true);
            o.setId(viewsHmiEntity.getId());
            viewsVOList.add(o);
        }

        return viewsVOList;
    }
}
